const { Service } = require('egg');
// const { generateRandomNumber } = require('../utils/randomUUID');
class ReservationService extends Service {
  // 获取数据库中得数据
  async getReservationList(page, pageSize) {
    try {
      if (page && pageSize) {
        const ReservationList = await this.app.model.Reservation.findAll({
          offset: (page - 1) * pageSize, // 查询的起始位置
          limit: Number(pageSize), // 限制返回的数据量 转换成整数u传给数据库否则会报错
        });
        return ReservationList;
      }
      const ReservationList = await this.app.model.Reservation.findAll();
      return ReservationList;
    } catch (error) {
      // 获取失败
      console.error(error);
      this.ctx.body = { message: '查询失败' };
    }
  }
  // 根据订单id查询订单信息
  async getReserListById(orderID) {
    const orderInfo = await this.app.model.Reservation.findAll({
      where: {
        orderID,
      },
    });
    if (!orderInfo) {
      this.ctx.status = 404;
      return;
    }
    return orderInfo;
  }
  // 创建新的订单
  async addReserList(data) {

    try {
      console.log('增加订单');
      // const orderID = generateRandomNumber();
      const addList = await this.app.model.Reservation.create(data);

      return addList;
    } catch (error) {
      this.ctx.logger.error(error);
      this.ctx.body = {
        code: error.code || 500,
        message: error.message || '服务器错误',
      };
    }

  }
  // 根据id删除数据
  async delReservation(id) {
    try {
      const delResult = await this.app.model.Reservation.findOne({
        where: { orderID: id },
      });
      if (delResult) {
        await delResult.destroy();
      } else {
        return '删除失败';
      }


      return delResult;
    } catch (error) {
      return '用户信息不存在';
    }
  }
  // 根据id修改数据
  async updateReservation(orderID, data) {
    try {
      // console.log('id-------', id, data);
      const updateResult = await this.ctx.model.Reservation.findOne({
        where: {
          orderID,
        },
      });
      if (updateResult) {
        await updateResult.update(data);
      } else {
        return '服务器错误';
      }
      // console.log(updateResult);
      return updateResult;
    } catch (error) {
      console.log(error);
    }
  }
}
module.exports = ReservationService;
